package org.bjf.demo;

import org.apache.commons.compress.utils.Lists;

import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * 批处理迭代器
 */
public class BatchDataIterator<T, P extends BatchDataIterator.DataProvider<T>> implements Iterator<T> {


    public BatchDataIterator(List<P> dataProviders) {
        this.dataProviders = dataProviders;
    }

    //分批查询条件
    private final List<P> dataProviders;
    private Iterator<T> currentIterator = Collections.emptyIterator();

    public void loadData() {
        if (currentIterator.hasNext()) {
            return;
        }
        if (dataProviders.isEmpty()) {
            return;
        }
        List<T> list = dataProviders.remove(0).loadData();
        if (list != null) {
            currentIterator = list.iterator();
        }
        loadData();
    }

    @Override
    public boolean hasNext() {
        loadData();
        return currentIterator.hasNext();
    }

    @Override
    public T next() {
        return currentIterator.next();
    }


    public interface DataProvider<T> {

        List<T> loadData();
    }

    //************************* 下面都是测试代码 *************************
    public static void main(String[] args) {
        List<ApiDataProvider> dataProviders = Lists.newArrayList();
        // 每个provider的
        dataProviders.add(new ApiDataProvider("A"));
        dataProviders.add(new ApiDataProvider("B"));
        dataProviders.add(new ApiDataProvider("D"));
        BatchDataIterator<String, ApiDataProvider> batchDataIterator =  new BatchDataIterator<>(dataProviders);

        while (batchDataIterator.hasNext()) {
            String next = batchDataIterator.next();
            System.out.println(next);
        }
    }

    public static class ApiDataProvider implements DataProvider<String> {

        private String condition;

        public ApiDataProvider(String condition) {
            this.condition = condition;
        }

        @Override
        public List<String> loadData() {
            // 查询数据
            return Arrays.asList(condition + "_" + 1, condition + "_" + 2);
        }
    }
}
